<template>
  <div class="page-container">
    <el-card>
      <VCategory />
    </el-card>

    <!-- 属性列表的结构 -->
    <el-card class="attr-list" v-show="isShowList">
      <el-row>
        <el-col :span="24">
          <el-button type="primary" :icon="Plus" :disabled="!category3Id" @click="showAddCard"
            >添加属性</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="attrList" style="width: 100%" border stripe>
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="attrName" label="属性名称" width="180" />
        <el-table-column label="属性值名称列表">
          <template #default="{ row }">
            <el-tag type="success" v-for="item in row.attrValueList" :key="item.id">
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default>
            <el-button size="small" type="warning" :icon="Edit" />
            <el-button size="small" type="danger" :icon="Delete" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增属性的结构 -->
    <el-card class="attr-list" v-show="!isShowList">
      <el-form :model="addEditData" :inline="true" label-width="60px">
        <el-form-item label="属性名">
          <el-input placeholder="请输入属性名" v-model="addEditData.attrName" />
        </el-form-item>
        <br />
        <el-form-item>
          <el-button type="primary" @click="addAttrValue">添加属性值</el-button>
          <el-button @click="handeCancel">取消</el-button>
        </el-form-item>
      </el-form>

      <el-table border stripe :data="addEditData.attrValueList">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column label="属性值名称">
          <template #default="{ row, $index }">
            <el-input
              ref="inputRef"
              v-if="row.isEdit"
              v-model="row.valueName"
              @blur="toSpan(row, $index)"
            />
            <span class="value-span" v-else @click="toInput(row)">
              {{ row.valueName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" />
      </el-table>

      <el-row class="add-form-row">
        <el-col :span="24">
          <el-button type="primary">保存</el-button>
          <el-button @click="handeCancel">取消</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useCategoryStore } from '@/stores/category'
import { storeToRefs } from 'pinia'
import { nextTick, ref, watch } from 'vue'
import { reqAttrList } from '@/api/Attr'
import type { IAttrValueItem, IReqAddEditAttr, IResAttrItem } from '@/types/attr'
import { ElMessage, type InputInstance } from 'element-plus'
// 对 Store 进行实例化
const categoryStore = useCategoryStore()
const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore)

// 创建 input 组件的引用
const inputRef = ref<InputInstance | null>(null)

// 控制列表的展示和隐藏
const isShowList = ref(true)

// 新增和编辑的数据
const addEditData = ref<IReqAddEditAttr>({
  attrName: '', // 属性名
  attrValueList: [], // 属性值列表
  categoryId: '', // 三级分类的 id
  categoryLevel: 3 // 分类等级
})

// 从 input 输入框切换到 span
const toSpan = (row: IAttrValueItem, index: number) => {
  // 判断用户是否输入了值
  if (row.valueName?.trim() === '') {
    // 在弹框显示之前，需要将所有的弹框先进行关掉
    ElMessage.closeAll()
    ElMessage.error('属性值不能为空！')
    // 如果没有输入值，需要将当前行删除
    addEditData.value.attrValueList.splice(index, 1)
    // 不让代码继续往下运行
    return
  }
  row.isEdit = false
}

// 从 span 切换到 input 输入框
const toInput = (row: IAttrValueItem) => {
  row.isEdit = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

// 点击添加属性值按钮添加属性值
const addAttrValue = () => {
  addEditData.value.attrValueList.push({
    valueName: '',
    isEdit: true
  })
  nextTick(() => {
    inputRef.value?.focus()
  })
}

// 新增结构的取消按钮
const handeCancel = () => {
  // 展示属性列表
  isShowList.value = true
}

// 点击添加属性按钮展示添加卡片结构
const showAddCard = () => {
  // 隐藏属性列表
  isShowList.value = false
  // 对分类进行赋值
  addEditData.value.categoryId = category3Id.value
}

//#region 属性管理的初始化
// 属性列表
const attrList = ref<IResAttrItem[]>([])

// 获取属性列表
const getAttrList = async () => {
  // 组织 API 函数需要的参数
  const params = {
    category1Id: category1Id.value,
    category2Id: category2Id.value,
    category3Id: category3Id.value
  }

  // 调用 API 函数，传递参数
  const res = await reqAttrList(params)

  if (res.code === 200) {
    attrList.value = res.data
  }
}

watch(
  category3Id,
  (newVal) => {
    if (!newVal) {
      // 如果三级分类 id 没有值，是空字符串，需要将属性列表重置为空
      attrList.value = []
    } else {
      // 如果三级分类 id 有值，获取属性列表
      getAttrList()
    }
  },
  {
    immediate: true
  }
)
//#endregion
</script>

<script lang="ts">
export default {
  name: 'AttrView'
}
</script>

<style lang="scss" scoped>
.attr-list,
.el-table {
  margin-top: 16px;
}
.el-tag {
  margin: 5px;
}
.value-span {
  display: block;
}
</style>
